﻿using LiveChartsCore.Defaults;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using UIWindows.Models.Homes;
using UIWindows.Tools.Helper;
using UIWindows.UserControls;
using XCode;
using XingLucifer.IBase.Enums;

namespace UIWindows.GlobalStatics
{
    [Attributes.Singleton]
    public class HomeStatic
    {
        public ObservableCollection<TrendModel> Trend { get; set; }
        public EquipmentTimeModel EquipmentTime { get; set; }
        public AsyncObservableCollection<MessageBeforeScanCodeModel> Battery_BeforeScanCode { get; set; }
        public AsyncObservableCollection<MessageShortCircuitModel> Battery_ShortCircuit { get; set; }
        public AsyncObservableCollection<MessageBeforeWeighingModel> Battery_BeforeWeighing { get; set; }
        public AsyncObservableCollection<MessageAfterWeighingModel> Battery_AfterWeighing { get; set; }
        public AsyncObservableCollection<Kinlo.Entitys.ProductionData> Battery_AfterFluidInjection { get; set; }

        public ChartDataModel ChartData { get; set; }
        public HomeStatic()
        {
            try
            {
                if (System.IO.File.Exists(GlobalStatic.EquipmentTimePath))
                {
                    EquipmentTime = System.Text.Json.JsonSerializer.Deserialize<EquipmentTimeModel>(System.IO.File.ReadAllText(GlobalStatic.EquipmentTimePath, Encoding.UTF8), GlobalStatic.Options);
                }
                else
                {
                    EquipmentTime = new EquipmentTimeModel();
                }
            }
            catch (Exception)
            {
                EquipmentTime = new EquipmentTimeModel();
            }
            Trend = new ObservableCollection<TrendModel>();
            try
            {
                if (System.IO.File.Exists(GlobalStatic.ChartDataPath))
                {
                    ChartData = System.Text.Json.JsonSerializer.Deserialize<ChartDataModel>(System.IO.File.ReadAllText(GlobalStatic.ChartDataPath, Encoding.UTF8), GlobalStatic.Options);
                }
                else
                {
                    ChartData = new ChartDataModel();
                }
            }
            catch (Exception)
            {
                ChartData = new ChartDataModel();
            }
            ChartData.OV_AfterWeighingPassingRate = new ObservableValue();
            ChartData.OV_LessLiquid = new ObservableValue();
            ChartData.OV_MultiLiquid = new ObservableValue();
            ChartData.OV_LiquidInjection_PassingRate = new ObservableValue();

            ChartData.OV_AfterWeighingPassingRate.Value = ChartData.AfterWeighingPassingRate;
            ChartData.OV_LessLiquid.Value = ChartData.NG_LessLiquid;
            ChartData.OV_MultiLiquid.Value = ChartData.NG_MultiLiquid;
            ChartData.OV_LiquidInjection_PassingRate.Value = ChartData.LiquidInjection_PassingRate;

            Battery_BeforeScanCode = new AsyncObservableCollection<MessageBeforeScanCodeModel>();
            Battery_ShortCircuit = new AsyncObservableCollection<MessageShortCircuitModel>();
            Battery_BeforeWeighing = new AsyncObservableCollection<MessageBeforeWeighingModel>();
            Battery_AfterWeighing = new AsyncObservableCollection<MessageAfterWeighingModel>();
            Battery_AfterFluidInjection = new AsyncObservableCollection<Kinlo.Entitys.ProductionData>();
        }

        public void SaveEquipmentTime() => System.IO.File.WriteAllText(GlobalStatic.EquipmentTimePath, System.Text.Json.JsonSerializer.Serialize(EquipmentTime, GlobalStatic.Options), Encoding.UTF8);
        public void SaveChartData() => System.IO.File.WriteAllText(GlobalStatic.ChartDataPath, System.Text.Json.JsonSerializer.Serialize(ChartData, GlobalStatic.Options), Encoding.UTF8);

        /// <summary>
        /// 前扫码信息输出
        /// </summary>
        /// <param name="barcode">条码</param>
        /// <param name="message">结果</param>
        /// <param name="dateTime">时间</param>
        public void AddInBattery(string barcode, ResultTypes message, DateTime dateTime, int location)
        {
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Battery_BeforeScanCode.Insert(0, new MessageBeforeScanCodeModel()
                    {
                        BarCode = barcode,
                        Location = location,
                        Result = message,
                        Time = dateTime.ToString("yyyy/MM/dd HH:mm:ss")
                    });
                    if (Battery_BeforeScanCode.Count > 400)
                    {
                        Battery_BeforeScanCode.RemoveAt(399);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    $"前扫码 第 [{i}] 次 插入日志异常：{ex.ToString().Trim()}".RunLog(MessageLevelType.错误);
                }
            }
        }

        /// <summary>
        /// 前称重信息输出
        /// </summary>
        /// <param name="barcode">条码</param>
        /// <param name="message">结果</param>
        /// <param name="dateTime">时间</param>
        /// <param name="production">实体</param>
        public void AddBeforeWeighingBattery(string barcode, ResultTypes message, DateTime dateTime, double weighing, int location, Kinlo.Entitys.ProductionData production)
        {
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Battery_BeforeWeighing.Insert(0, new MessageBeforeWeighingModel()
                    {
                        BarCode = barcode,
                        Result = message,
                        Time = dateTime.ToString("yyyy/MM/dd HH:mm:ss"),
                        FormerWeighing = weighing,
                        LocationFormerWeighing = production.LocationFormerWeighing,
                        RangeForeweigh = production?.RangeForeweigh ?? string.Empty,
                        TargetInjectionVolume = production?.TargetInjectionVolume ?? 0,
                        NetWeight = production?.NetWeight ?? 0,
                        OneAfterWeighing = production?.OneAfterWeighing ?? 0,
                    });
                    if (Battery_BeforeWeighing.Count > 400)
                    {
                        Battery_BeforeWeighing.RemoveAt(399);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    $"前称重 第 [{i}] 次 插入日志异常：{ex.ToString().Trim()}".RunLog(MessageLevelType.错误);
                }
            }
        }
        /// <summary>
        /// 后称重信息输出
        /// </summary>
        /// <param name="barcode">条码</param>
        /// <param name="message">结果</param>
        /// <param name="dateTime">时间</param>
        /// <param name="production">实体</param>
        public void AddAfertWeighingBattery(string barcode, ResultTypes message, DateTime dateTime, double weighing, int location, Kinlo.Entitys.ProductionData production)
        {
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Battery_AfterWeighing.Insert(0, new MessageAfterWeighingModel()
                    {
                        BarCode = barcode,
                        Result = production.ResultTotal,
                        LocationAfterWeighing= production.LocationAfterWeighing,
                        LocationFormerWeighing = production.LocationFormerWeighing,
                        FormerWeighing = production.FormerWeighing,
                        AfterWeighing = production.AfterWeighing,
                        TargetInjectionVolume = production.TargetInjectionVolume,
                        ActualInjectionVolume = production.ActualInjectionVolume,
                        InjectionVolumeDeviationValue = production.InjectionVolumeDeviationValue,
                        ActualTotalInjectionVolume= production.ActualTotalInjectionVolume,
                        RangeForeweigh = production.RangeForeweigh,
                        RangeAfterWeighing = production.RangeAfterWeighing,
                        RangeFluidRate = production.RangeFluidRate,
                        LeakResult = production.LeakResult,
                        ResultFormerWeighing = production.ResultFormerWeighing,
                        ResultAfterWeighing = production.ResultAfterWeighing,
                        TimeFormerWeighing = production.TimeFormerWeighing.GetDateTime().ToString("yyyy/MM/dd HH:mm:ss"),
                        TimeAfterWeighing = production.TimeAfterWeighing.GetDateTime().ToString("yyyy/MM/dd HH:mm:ss"),
                    });
                    if (Battery_BeforeWeighing.Count > 400)
                    {
                        Battery_BeforeWeighing.RemoveAt(399);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    $"前称重 第 [{i}] 次 插入日志异常：{ex.ToString().Trim()}".RunLog(MessageLevelType.错误);
                }
            }
        }

        private Action<Kinlo.Entitys.ProductionData, Kinlo.Entitys.ProductionData> _batteryInjectionUpdate;
        /// <summary>
        /// 注液后工序图表
        /// </summary>
        /// <param name="production"></param>
        public void AddOutBattery(Kinlo.Entitys.ProductionData production)
        {
            var model = Battery_AfterFluidInjection.FirstOrDefault(x => x.SnowflakeId == production.SnowflakeId);
            if (_batteryInjectionUpdate == null)
            {
                _batteryInjectionUpdate = ConversionHelper.CopyXCodeEntity<Kinlo.Entitys.ProductionData, Kinlo.Entitys.ProductionData>();
            }
            if (model != null)
            {
                _batteryInjectionUpdate.Invoke(production, model);
                return;
            }
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Battery_AfterFluidInjection.Insert(0, production);
                    if (Battery_AfterFluidInjection.Count > 400)
                    {
                        Battery_AfterFluidInjection.RemoveAt(399);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    $"注液后 第 [{i}] 次 插入日志异常：{ex.ToString().Trim()}".RunLog(MessageLevelType.错误);
                }
            }
        }

        /// <summary>
        /// 短路测试仪
        /// </summary>
        /// <param name="barcode">条码</param>
        /// <param name="message">信息</param>
        /// <param name="dateTime">时间</param>
        /// <param name="production">实体</param>
        public void AddShortCircuitBattery(string barcode, Kinlo.Entitys.ProductionData production)
        {
            var model = Battery_ShortCircuit.FirstOrDefault(x => x.SnowflakeId == production.SnowflakeId);
            if (model != null)
            {
                //model.ResistanceTestTime = production.TimeHousing.ToString("yyyy/MM/dd HH:mm:ss");
                //model.ResistanceTestValue = production.ResistanceTestValue;
                return;
            }
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Battery_ShortCircuit.Insert(0, new MessageShortCircuitModel()
                    {
                        BarCode = barcode,
                        Location = production.LocationShortCircuitTester,
                        SnowflakeId = production.SnowflakeId,
                        Result = production.ResultShortCicute,
                        ElectrodesTestValue = production.ResistanceTestValue,
                        ElectrodesCapacitance = production.ShellShortCicuteCapacitance,
                        ElectrodesTestTime = production.TimeElectrodes.GetDateTime().ToString("yyyy/MM/dd HH:mm:ss"),
                        VP电压 = production.ShellShortCicuteVoltage,
                        跌落1 = production.FallOne,
                        跌落2 = production.FallTwo,
                        跌落3 = production.FallThree,
                        升压时间 = production.BoostTime,
                        开路结果 = production.ShellShortCicuteOpenCircuitResult,
                        放电1结果 = production.ShellShortCicuteDischargeOneResult,
                        放电2结果 = production.ShellShortCicuteDischargeTwoResult,
                        VP结果 = production.ShellShortCicuteVoltageResult,
                        跌落1结果 = production.ShellShortCicuteFallOneResult,
                        跌落2结果 = production.ShellShortCicuteFallTwoResult,
                        跌落3结果 = production.ShellShortCicuteFallThreeResult,
                        TL结果 = production.ShellShortCicuteTLResult,
                        TH结果 = production.ShellShortCicuteTHResult,
                        电阻测试结果 = production.ShellShortCicuteResistanceTestResult,
                        电容测试结果 = production.ShellShortCicuteCapacitanceResult,

                    });
                    if (Battery_ShortCircuit.Count > 400)
                    {
                        Battery_ShortCircuit.RemoveAt(399);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    $"短路测试 第 [{i}] 次 插入日志异常：{ex.ToString().Trim()}".RunLog(MessageLevelType.错误);
                }
            }
        }
    }
}
